package com.lb.shopguide.ui.fragment.guide.recommend;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.RelativeSizeSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.JsonArray;
import com.google.zxing.WriterException;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.R;
import com.lb.shopguide.adapter.AdapterMaterialGoods;
import com.lb.shopguide.base.BaseCommonFragment;
import com.lb.shopguide.base.BaseFragment;
import com.lb.shopguide.config.AppConfigManager;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.entity.recommend.MaterialGoodsBean;
import com.lb.shopguide.entity.recommend.RecBannerBean;
import com.lb.shopguide.http.method.ApiMethodGuide;
import com.lb.shopguide.ui.activity.ActivityActivityDetail;
import com.lb.shopguide.ui.activity.GuideMainActivity;
import com.lb.shopguide.ui.dialog.DialogShare2Circle;
import com.lb.shopguide.ui.view.NormalTitleBar;
import com.lb.shopguide.util.FileUtilsExt;
import com.lb.shopguide.util.json.JsonUtil;
import com.lb.shopguide.util.lb.AdJumpUtil;
import com.lb.shopguide.util.lb.BarcodeUtil;
import com.lb.shopguide.util.lb.BizUtil;
import com.lb.shopguide.util.pic.ImageLoaderUtils;
import com.qmuiteam.qmui.util.QMUIDrawableHelper;
import com.trello.rxlifecycle2.android.FragmentEvent;
import com.xiasuhuei321.loadingdialog.view.LoadingDialog;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;

/**
 * Create by kangzhao on 2018/11/25
 */
public class FragmentMaterialGoods extends BaseCommonFragment implements SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener {
    @BindView(R.id.ntb)
    NormalTitleBar ntb;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @BindView(R.id.layout_share_image)
    LinearLayout layoutShareImage;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;

    private List<MaterialGoodsBean> mMaterialGoodsList;
    private AdapterMaterialGoods mAdapterMaterialsGoods;

    private MaterialGoodsBean mMaterialGoodsBean;
    private LoadingDialog ld;


    //    private List<String> imgList;
    private String shareUrl;

    public static FragmentMaterialGoods newInstance() {
        return new FragmentMaterialGoods();
    }

    @Override
    public void onRefresh() {
        mMaterialGoodsList = new ArrayList<>();
        initRequest();
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_material_goods;
    }

    @Override
    public void initData() {
//        imgList = new ArrayList<>();
        mMaterialGoodsList = new ArrayList<>();
        initRequest();
    }

    @Override
    public void initView() {

        ntb.setLeftImageSrc(R.drawable.iv_back);
        ntb.setTitleText("全部必推素材商品");
        ntb.setOnLeftImageListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop();
            }
        });

        noDataView = LayoutInflater.from(mContext).inflate(R.layout.layout_empty_view, (ViewGroup) mRecyclerView.getParent(), false);
        TextView tvEmpty = noDataView.findViewById(R.id.tv_empty);
        tvEmpty.setText("暂无素材商品");
        errorView = LayoutInflater.from(mContext).inflate(R.layout.layout_error_view, (ViewGroup) mRecyclerView.getParent(), false);
        noDataView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onRefresh();
            }
        });
        errorView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onRefresh();
            }
        });

        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.setColorSchemeColors(Color.rgb(253, 91, 89));

        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));

        mAdapterMaterialsGoods = new AdapterMaterialGoods(R.layout.item_material_goods, mMaterialGoodsList, this);
        mRecyclerView.setAdapter(mAdapterMaterialsGoods);
        initListener();
    }

    private void addHeaderView(RecBannerBean bean) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.layout_banner_top, null);
        ImageView ivBanner = view.findViewById(R.id.iv_banner);
        int width = ScreenUtils.getScreenWidth();
        float aspect = 0.432f;
        int height = (int) (width * aspect);
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) ivBanner.getLayoutParams();
        params.width = width;
        params.height = height;
        ivBanner.setLayoutParams(params);
        ImageLoaderUtils.display(mContext, ivBanner, bean.getBannerPicUrl());
        mAdapterMaterialsGoods.addHeaderView(view);
        ivBanner.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bean.setJumpUrl(BizUtil.fixActivityUrl(bean.getJumpUrl(), "XD0012"));
                jumpLogic(bean);
            }
        });
    }

    private void jumpLogic(RecBannerBean bean) {
        BaseFragment fragment = AdJumpUtil.jumpToDestination(bean.getJumpMode(), bean.getPageSdCode(), bean.getRelCode(), bean.getRelName(), bean.getJumpUrl());
        if (fragment instanceof FragmentRecommendHome) {
            pop();
        } else if (fragment instanceof FragmentVirtualActivity) {
            Intent intent = new Intent(getContext(), ActivityActivityDetail.class);
            Bundle bundle = new Bundle();
            bundle.putString(AppConstant.WEB_URL, fragment.getArguments().getString(AppConstant.WEB_URL));
            bundle.putString(AppConstant.WEB_TITLE, fragment.getArguments().getString(AppConstant.WEB_TITLE));
            intent.putExtras(bundle);
            startActivity(intent);
        } else {
            start(fragment);
        }
    }

    private void initListener() {
        mAdapterMaterialsGoods.setOnMaterialListener(new AdapterMaterialGoods.OnMaterialListener() {
            @Override
            public void onShareCircle(MaterialGoodsBean bean) {
                ld = new LoadingDialog(mContext);
                ld.setLoadingText("处理中")
                        .setInterceptBack(true)
                        .setLoadSpeed(LoadingDialog.Speed.SPEED_ONE)
                        .show();
                ld.show();
                mMaterialGoodsBean = bean;
                ImageView ivGoods = layoutShareImage.findViewById(R.id.iv_goods);
                ImageView ivBarcode = layoutShareImage.findViewById(R.id.iv_barcode);
                int orderEntranceCode = AppConstant.MATERIAL_GOODS;
                if (AppConfigManager.getAppconfigManager(mContext).getDevMode() == AppConstant.KEY_RUN_MODE_FORMAL) {
                    shareUrl = "https://singlepage.storeer.com/activity_2018/eightHalf_index?productCode=" + mMaterialGoodsBean.getProductCode() + "&appEntranceType=" +
                            AppConstant.APP_ENTRANCE_ANDROID + "&linkStaffCode=" + mUserConfigManager.getUserId() + "&xd_code=XD0008" + "&orderEntryCode=" + orderEntranceCode + "&productType=" + AppConstant.PTYPE_MATERIAL_GOODS;
                } else {
                    shareUrl = "https://sintest.storeer.com/activity_2018/eightHalf_index?productCode=" + mMaterialGoodsBean.getProductCode() + "&appEntranceType=" +
                            AppConstant.APP_ENTRANCE_ANDROID + "&linkStaffCode=" + mUserConfigManager.getUserId() + "&xd_code=XD0008" + "&orderEntryCode=" + orderEntranceCode + "&productType=" + AppConstant.PTYPE_MATERIAL_GOODS;
                }
                try {
                    Bitmap bitmap = BarcodeUtil.createQRCode(shareUrl, SizeUtils.dp2px(95));
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();//https://qr.alipay.com/bax05663gkt4hkscus65602d
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
                    byte[] bytes = baos.toByteArray();
                    RequestOptions requestOptions = new RequestOptions()
                            .fitCenter()
                            .error(R.drawable.iv_default_avatar)
                            .priority(Priority.HIGH)
                            .diskCacheStrategy(DiskCacheStrategy.NONE);
                    ImageLoaderUtils.getGlideManager().load(bytes).apply(requestOptions).into(ivBarcode);
                } catch (WriterException e) {
                    e.printStackTrace();
                }
                TextView tvGoodsName = layoutShareImage.findViewById(R.id.tv_share_goods_name);
                TextView tvOriginPrice = layoutShareImage.findViewById(R.id.tv_share_price_origin);
                tvOriginPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                TextView tvSalePrice = layoutShareImage.findViewById(R.id.tv_share_price);
                LinearLayout layoutLimit = layoutShareImage.findViewById(R.id.layout_sec);
                TextView tvLimitTime = layoutShareImage.findViewById(R.id.tv_limit_time);
                TextView tvSaleHour = layoutShareImage.findViewById(R.id.tv_sale_hour);
                if (bean.isSecSymbol()) {
                    if (bean.getSecStatus() == AppConstant.GOODS_SEC_NOT_START) {
                        Date date = TimeUtils.millis2Date(bean.getSecBeginTimeStamp());
                        Calendar cal = Calendar.getInstance();
                        cal.setTime(date);
                        if (TimeUtils.isToday(date)) {
                            tvLimitTime.setText("今天 " + cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE) + "开始");
                        } else {
                            tvLimitTime.setText(cal.get(Calendar.MONTH) + 1 + "-" + cal.get(Calendar.DAY_OF_MONTH) + " " + cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE) + "开始");
                        }
                        tvSaleHour.setVisibility(View.VISIBLE);
                        long period = bean.getSecEndTimeStamp() - bean.getSecBeginTimeStamp();
                        tvSaleHour.setText("仅售卖" + BizUtil.formatDuring(period));
                    } else if (bean.getSecStatus() == AppConstant.GOODS_SEC_START) {
                        Date date = TimeUtils.millis2Date(bean.getSecEndTimeStamp());
                        Calendar cal = Calendar.getInstance();
                        cal.setTime(date);
                        if (TimeUtils.isToday(date)) {
                            tvLimitTime.setText("今天 " + cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE) + "结束");
                        } else {
                            tvLimitTime.setText(cal.get(Calendar.MONTH) + 1 + "-" + cal.get(Calendar.DAY_OF_MONTH) + " " + cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE) + "结束");
                        }
                        tvSaleHour.setVisibility(View.GONE);
                    }
                    layoutLimit.setVisibility(View.VISIBLE);
                } else {
                    layoutLimit.setVisibility(View.GONE);
                }
                ImageLoaderUtils.display(mContext, ivGoods, bean.getSharePicUrls().get(bean.getSharePicUrls().size() - 1));
                tvGoodsName.setText(bean.getProductName());
                tvOriginPrice.setText("￥" + bean.getOrgPrice());
                tvSalePrice.setText("￥" + bean.getSalePrice());
                SpannableString sp = new SpannableString(tvSalePrice.getText().toString());
                sp.setSpan(new RelativeSizeSpan(0.5f), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  //0.5f表示
                tvSalePrice.setText(sp);
                boolean result = BizUtil.copyToClipboard(mContext, bean.getMatText());
                if (result) {
                    ivBarcode.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            ld.close();
                            showShareDialog();
                        }
                    }, 1500);
                }
                if (result) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            List<String> urls = bean.getSharePicUrls();
                            for (int i = 0; i < urls.size(); i++) {
                                String name = i + bean.getProductCode() + AppConstant.PNG;
                                if (i != urls.size() - 1) {
                                    FileUtilsExt.saveImageToGallery(mContext, name, BizUtil.getBitmapByUrl(BizUtil.addSlimParam(urls.get(i))));
                                }else {
                                    FileUtilsExt.saveImageToGallery(mContext, name, QMUIDrawableHelper.createBitmapFromView(layoutShareImage));
                                }
                            }
//                            Message msg = Message.obtain();
//                            msg.what = 0;
//                            myHandler.sendMessageDelayed(msg, 500);
                        }
                    }).start();
                }
            }

            @Override
            public void viewImage(int position, List<String> urls) {
                start(FragmentGoodsImage.newInstance(position, urls));
            }
        });
    }


    @Override
    public void finishRefresh() {
        mSwipeRefreshLayout.setRefreshing(false);
        mAdapterMaterialsGoods.loadMoreComplete();
    }

    @Override
    public void sessionOutOfDate() {
        ((GuideMainActivity) _mActivity).onSessionOutOfDate();
    }

    @Override
    public void requestError(String error) {
        mSwipeRefreshLayout.setRefreshing(false);
    }

    @Override
    public String getPageTag() {
        return FragmentMaterialGoods.class.getCanonicalName();
    }

    private void bindBanner(RecBannerBean bean) {
        if (mAdapterMaterialsGoods.getHeaderLayoutCount() == 0) {
            addHeaderView(bean);
        }
    }

    private void showShareDialog() {
        DialogShare2Circle dialogShare2Circle = DialogShare2Circle.getDialogShare2Circle(AppConstant.BANNER_TYPE_SHARE_MATERIAL, mMaterialGoodsBean.getProductCode());
        dialogShare2Circle.show(getFragmentManager(), getPageTag());
        dialogShare2Circle.setOnDialogClickListener(new DialogShare2Circle.OnDialogClickListener() {
            @Override
            public void onBannerClick(RecBannerBean bean) {
                dialogShare2Circle.dismissAllowingStateLoss();
                jumpLogic(bean);
            }

            @Override
            public void onShareCircle() {
//                String[] imgArray = new String[imgList.size()];
//                imgList.toArray(imgArray);
//                BizUtil.share(mContext, mMaterialGoodsBean.getProductName(), mMaterialGoodsBean.getProductName(), shareUrl, imgList.get(imgList.size() - 1), AppConstant.SHARE_WECHAT_CIRCLE, "");
                BizUtil.jumpToWechat(mContext);
            }
        });
    }


    private void bindMaterialGoods() {
        mAdapterMaterialsGoods.setNewData(mMaterialGoodsList);
        if (mAdapterMaterialsGoods.getFooterLayoutCount() == 0) {
            View footer = LayoutInflater.from(mContext).inflate(R.layout.layout_rec_common_footer, null);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, SizeUtils.dp2px(56));
            footer.setLayoutParams(params);
            mAdapterMaterialsGoods.addFooterView(footer);
        }
    }

    @SuppressLint("HandlerLeak")
    Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                showShareDialog();
                hideLoading();
            }
        }
    };

    private void hideLoading() {
        ld.close();
    }

    private void initRequest() {
        getMaterialGoods();
        getAdBanner();
    }

    private void getMaterialGoods() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    JsonArray jsonArray = JsonUtil.getJsonArrayFromMap(response.getReturnContent());
                    for (int i = 0; i < jsonArray.size(); i++) {
                        MaterialGoodsBean bean = JsonUtil.getGson().fromJson(jsonArray.get(i), MaterialGoodsBean.class);
                        mMaterialGoodsList.add(bean);
                    }
                    bindMaterialGoods();
                } else {
                    ToastUtils.showShort(response.getMessage());
                    mRecyclerView.setVisibility(View.GONE);
                }
                finishRefresh();
            }
        };
        ApiMethodGuide.listMaterialProduct(new SimpleLbObserver(listener, otherListener), this, FragmentEvent.DESTROY_VIEW);
    }

    private void getAdBanner() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    RecBannerBean bean = (RecBannerBean) JsonUtil.getObject(response.getReturnContent(), RecBannerBean.class);
                    bindBanner(bean);
                }
            }
        };
        ApiMethodGuide.getAdBanner(AppConstant.BANNER_TYPE_ALL_MATERIAL, new SimpleLbObserver(listener, otherListener), this, FragmentEvent.DESTROY_VIEW);
    }

    @Override
    public void onLoadMoreRequested() {

    }
}
